package com.xz.danhuaapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.xz.danhuaapi.common.ErrorCode;
import com.xz.danhuaapi.exception.BusinessException;
import com.xz.danhuaapi.exception.ThrowUtils;
import com.xz.danhuaapi.mapper.InterfaceInfoMapper;
import com.xz.danhuaapi.model.dto.interfaceinfo.InterfaceInfoAddRequest;
import com.xz.danhuaapi.model.dto.interfaceinfo.InterfaceInfoInvokeRequest;
import com.xz.danhuaapi.model.dto.interfaceinfo.InterfaceInfoQueryRequest;
import com.xz.danhuaapi.model.enums.InterfaceInfoStatusEnum;
import com.xz.danhuaapi.model.vo.InterfaceInfoVO;
import com.xz.danhuaapi.model.vo.UserVO;
import com.xz.danhuaapi.service.InterfaceInfoService;
import com.xz.danhuaapi.service.UserService;
import com.xz.danhuaapiclientsdk.client.DanHuaApiClient;
import com.xz.danhuaapicommon.model.entity.InterfaceInfo;
import com.xz.danhuaapicommon.model.entity.User;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static com.xz.danhuaapi.constant.CommonConstant.SORT_ORDER_ASC;
import static com.xz.danhuaapi.constant.CommonConstant.SORT_ORDER_DESC;

/**
 * @author xuzhou
 * @description 针对表【interface_info(接口信息)】的数据库操作Service实现
 * @createDate 2024-07-04 14:46:33
 */
@Service
public class InterfaceInfoServiceImpl extends ServiceImpl<InterfaceInfoMapper, InterfaceInfo>
        implements InterfaceInfoService {

    @Resource
    private UserService userService;

    @Resource
    private DanHuaApiClient danHuaApiClient;

    @Override
    public void validInterfaceInfo(InterfaceInfo interfaceInfo, boolean add) {
        ThrowUtils.throwIfNull(interfaceInfo);
        String name = interfaceInfo.getName();
        String url = interfaceInfo.getUrl();
        String host = interfaceInfo.getHost();
        String requestParams = interfaceInfo.getRequestParams();
        String requestHeader = interfaceInfo.getRequestHeader();
        String responseHeader = interfaceInfo.getResponseHeader();
        String method = interfaceInfo.getMethod();

        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(name, url, requestParams, requestHeader, responseHeader, method, host), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
//        if (StringUtils.isNotBlank(title) && title.length() > 80) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题过长");
//        }
//        if (StringUtils.isNotBlank(content) && content.length() > 8192) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容过长");
//        }
    }

    /**
     * 获取查询包装类
     *
     * @param interfaceInfoQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<InterfaceInfo> getQueryWrapper(InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>();
        ThrowUtils.throwIfNull(interfaceInfoQueryRequest);

        String name = interfaceInfoQueryRequest.getName();
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);

        String description = interfaceInfoQueryRequest.getDescription();
        queryWrapper.like(StringUtils.isNotBlank(description), "description", description);

        String host = interfaceInfoQueryRequest.getHost();
        queryWrapper.like(StringUtils.isNotBlank(host), "host", host);

        String url = interfaceInfoQueryRequest.getUrl();
        queryWrapper.like(StringUtils.isNotBlank(url), "url", url);

        String requestHeader = interfaceInfoQueryRequest.getRequestHeader();
        queryWrapper.like(StringUtils.isNotBlank(requestHeader), "request_header", requestHeader);

        String responseHeader = interfaceInfoQueryRequest.getResponseHeader();
        queryWrapper.like(StringUtils.isNotBlank(responseHeader), "response_header", responseHeader);

        String requestParams = interfaceInfoQueryRequest.getRequestParams();
        queryWrapper.like(StringUtils.isNotBlank(requestParams), "request_params", requestParams);

        String method = interfaceInfoQueryRequest.getMethod();
        queryWrapper.like(StringUtils.isNotBlank(method), "method", method);

        String sortField = interfaceInfoQueryRequest.getSortField();
        String sortOrder = interfaceInfoQueryRequest.getSortOrder();
        if (SORT_ORDER_ASC.equals(sortOrder)) {
            // 升序
            if (StringUtils.isNotBlank(sortField)) {
                queryWrapper.orderByAsc(sortField);
            } else {
                queryWrapper.orderByAsc("create_time");
            }
        }
        if (SORT_ORDER_DESC.equals(sortOrder)) {
            // 降序
            if (StringUtils.isNotBlank(sortField)) {
                queryWrapper.orderByDesc(sortField);
            } else {
                queryWrapper.orderByDesc("create_time");
            }
        }

        return queryWrapper;
    }

    @Override
    public InterfaceInfoVO getInterfaceInfoVO(InterfaceInfo interfaceInfo) {
        InterfaceInfoVO interfaceInfoVO = InterfaceInfoVO.objToVo(interfaceInfo);

        Long userId = interfaceInfo.getUserId();
        ThrowUtils.throwIf((userId == null || userId <= 0), ErrorCode.PARAMS_ERROR);
        User crateUser = userService.getById(userId);

        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(crateUser, userVO);
        interfaceInfoVO.setUser(userVO);

        return interfaceInfoVO;
    }

    @Override
    public IPage<InterfaceInfoVO> getInterfaceInfoVOPage(Page<InterfaceInfo> interfaceInfoPage, HttpServletRequest request) {
        // 取出数据
        List<InterfaceInfo> interfaceinfoList = interfaceInfoPage.getRecords();
        if (CollectionUtils.isEmpty(interfaceinfoList)) {
            return new Page<>();
        }
        // 拷贝
        Page<InterfaceInfoVO> interfaceInfoVOPage = new Page<>();
        BeanUtils.copyProperties(interfaceInfoPage, interfaceInfoVOPage);

        // 关联查询用户信息 getInterfaceInfoVO
        List<InterfaceInfoVO> collect = interfaceinfoList.stream().map(this::getInterfaceInfoVO).collect(Collectors.toList());

        // 修改 数据内容
        interfaceInfoVOPage.setRecords(collect);

        return interfaceInfoVOPage;
    }

    @Override
    public long addInterfaceInfo(InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {

        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);

        this.validInterfaceInfo(interfaceInfo, true);
        User loginUser = userService.getLoginUser(request);
        interfaceInfo.setUserId(loginUser.getId());

        boolean result = this.save(interfaceInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        long newInterfaceInfoId = interfaceInfo.getId();

        return newInterfaceInfoId;
    }

    @Override
    public boolean onlineInterfaceInfo(Long id) {
        // 校验接口是否存在
        InterfaceInfo oldInterfaceInfo = this.getById(id);
        ThrowUtils.throwIfNull(oldInterfaceInfo);
        // 判断该接口是否可以调用
        com.xz.danhuaapiclientsdk.model.User user = new com.xz.danhuaapiclientsdk.model.User();
        user.setUsername("xuzhou");
        String username = danHuaApiClient.postNameJson(user);
        ThrowUtils.throwIfNull(username, ErrorCode.SYSTEM_ERROR, "接口验证失败");

        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setId(id);
        // 修改接口数据库中的状态字段为上线
        interfaceInfo.setStatus(InterfaceInfoStatusEnum.ONLINE.getValue());
        // 调用interfaceInfoService的updateById方法，传入interfaceInfo对象，并将返回的结果赋值给result变量
        return this.updateById(interfaceInfo);
    }

    @Override
    public boolean offlineInterfaceInfo(Long id) {
        // 校验接口是否存在
        InterfaceInfo oldInterfaceInfo = this.getById(id);
        ThrowUtils.throwIfNull(oldInterfaceInfo);

        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setId(id);
        // 修改接口数据库中的状态字段为上线
        interfaceInfo.setStatus(InterfaceInfoStatusEnum.OFFLINE.getValue());
        // 调用interfaceInfoService的updateById方法，传入interfaceInfo对象，并将返回的结果赋值给result变量
        return this.updateById(interfaceInfo);
    }

    @Override
    public Object invokeInterfaceInfo(InterfaceInfoInvokeRequest interfaceInfoInvokeRequest,
                                      HttpServletRequest request) {
        Long id = interfaceInfoInvokeRequest.getId();
        // 获取用户请求参数
        String userRequestParams = interfaceInfoInvokeRequest.getUserRequestParams();

        // 判断接口是否存在
        InterfaceInfo oldInterfaceInfo = this.getById(id);
        ThrowUtils.throwIfNull(oldInterfaceInfo);
        // 检查接口是否为下线的状态
        if (oldInterfaceInfo.getStatus().equals(InterfaceInfoStatusEnum.OFFLINE.getValue())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口已下线");
        }
        // 获取当前登录用户的ak和sk，这样相当于用户自己的这个身份去调用，
        // 也不会担心它刷接口，因为知道是谁刷了这个接口，会比较安全
        User loginUser = userService.getLoginUser(request);
        String accessKey = loginUser.getAccessKey();
        String secretKey = loginUser.getSecretKey();
        // 我们只需要进行测试调用，所以我们需要解析传递过来的参数。
        Gson gson = new Gson();
        com.xz.danhuaapiclientsdk.model.User user = gson.fromJson(userRequestParams, com.xz.danhuaapiclientsdk.model.User.class);
        DanHuaApiClient tempApiClient = new DanHuaApiClient(accessKey, secretKey);
        return tempApiClient.postNameJson(user);
    }
}




